<template>
 <el-card class="userinfo-container">
    <!-- 面板屑导航 -->
    <!-- separator 分隔符 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>基本资料</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :model="infoForm" :rules="infoRuels" ref="infoRef" label-width="100px">
      <el-form-item label="登录名称">
        <el-input v-model="infoForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="infoForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="infoForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
        <el-button @click="ressetinfo">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqUpdateUserInfo } from '@/api/user'
import { mapActions, mapState } from 'vuex'

export default {
  name: 'UserInfo',
  data () {
    return {
      infoForm: {
        nickname: '',
        email: ''
      },
      // 验证规则对象
      infoRuels: {
        nickname: [
          { required: true, message: '昵称不能为空', trigger: ['blur', 'change'] },
          { pattern: /^\S{1,10}$/, message: '昵称是1-10个非空字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: ['blur', 'change'] },
          { pattern: /^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/, message: '邮箱格式不正确', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  async created () {
    await this.getUserInfo()
    this.infoForm = { ...this.userInfo }
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    // 重置
    ressetinfo () {
      this.infoForm = { ...this.userInfo }
      this.$rpefs.infoRef.resetFields()
    },
    // 提交
    updateUserInfo () {
      this.$refs.infoRef.validate(async (flag) => {
        if (!flag) return console.log('校验失败')
        const { data } = await reqUpdateUserInfo(this.infoForm)
        console.log(data)
        if (data.code !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)
        this.getUserInfo()
      })
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  }
}
</script>

<style>

</style>
